<template>
    <div class="topic-creation-container">
        <div class="header-section"
            style="padding-left: 24px; height: 43.67px; margin: 0; font-family: Arial, PingFang SC, Microsoft YaHei, Helvetica Neue, Helvetica, Hiragino Sans GB; font-size: 14px; font-weight: 700; display: flex; align-items: center; background: #fff; border-bottom: 1px solid #e4e7ed;">
            <div>
                <el-button type="text" @click="handleUnselectCourse" style="padding: 0; margin: 0; color: #606266;"
                    :disabled="!selectCourse">
                    <i class="el-icon-caret-right" style="font-size: 18px; padding-right: 12px;"></i>
                </el-button>
            </div>
            {{ selectCourse ? selectCourse.title : '请选择课程' }}
        </div>

        <div class="content-wrapper" style="padding: 16px 24px; height: calc(100vh - 140px); overflow-y: auto;">
            <div v-if="!selectCourse" class="no-course-selected">
                <el-empty description="请先选择课程">
                    <el-icon style="font-size: 48px; color: #c0c4cc;">
                        <i class="el-icon-warning"></i>
                    </el-icon>
                </el-empty>
            </div>

            <div v-else>
                <div class="knowledge-header">
                    <h3>知识点选择</h3>
                    <div>
                        <el-button size="small" type="primary" @click="selectAll" :disabled="!knowledgeData.length">
                            全选
                        </el-button>
                        <el-button size="small" @click="clearAll" :disabled="!selectedKnowledge.length">
                            清空
                        </el-button>
                        <span class="selected-count">已选择: {{ selectedKnowledge.length }} 个知识点</span>
                    </div>

                </div>

                <div v-if="knowledgeData.length === 0" class="loading-state">
                    <el-icon class="is-loading">
                        <i class="el-icon-loading"></i>
                    </el-icon>
                    正在加载知识点...
                </div>

                <el-tree v-else :data="knowledgeData" :props="treeProps" show-checkbox node-key="id" ref="knowledgeTree"
                    @check="handleNodeCheck" :default-expanded-keys="expandedKeys" class="knowledge-tree">
                    <template #default="{ node, data }">
                        <div class="custom-tree-node">
                            <div class="node-label">
                                <el-tag :type="getNodeTagType(data.type)" size="mini" class="node-type-tag">
                                    {{ getNodeTypeLabel(data.type) }}
                                </el-tag>
                                <span class="node-title">{{ data.label }}</span>
                            </div>
                            <div v-if="data.content" class="node-content">
                                {{ data.content }}
                            </div>
                        </div>
                    </template>
                </el-tree>

                <!-- 已选择的知识点展示 -->
                <div v-if="selectedKnowledge.length > 0" class="selected-knowledge">
                    <el-divider content-position="left">已选择的知识点</el-divider>
                    <div class="selected-items">
                        <el-tag v-for="item in selectedKnowledge" :key="item.id" closable
                            @close="removeSelectedItem(item.id)" class="selected-tag">
                            {{ item.label }}
                        </el-tag>
                    </div>
                </div>

                <!-- 题目生成组件 -->
                <QuestionGeneration :selectedKnowledge="selectedKnowledge"
                    :courseId="selectCourse ? selectCourse.id : ''" @question-generated="handleQuestionGenerated"
                    @question-saved="handleQuestionSaved" @questions-updated="handleQuestionsUpdated" />
            </div>
        </div>

        <!-- 课程切换确认对话框 -->
        <CourseSwitchConfirm :visible.sync="showSwitchConfirm" :selectedKnowledgeCount="selectedKnowledge.length"
            :actionType="confirmActionType" @confirm="handleSwitchConfirm" @cancel="handleSwitchCancel" />
    </div>
</template>

<script>
import { fetchKnowledge } from '../../../../../api/exam/exam';
import QuestionGeneration from './QuestionGeneration.vue';
import CourseSwitchConfirm from './CourseSwitchConfirm.vue';

export default {
    name: 'TopicCreation',
    components: {
        QuestionGeneration,
        CourseSwitchConfirm
    },
    props: ['selectCourse'],
    data() {
        return {
            knowledgeData: [],
            selectedKnowledge: [], // 存储选中的知识点
            treeProps: {
                children: 'children',
                label: 'label'
            },
            expandedKeys: [], // 默认展开的节点
            showSwitchConfirm: false, // 控制课程切换确认对话框的显示
            confirmActionType: '', // 确认操作类型：'switch' 或 'close'
            pendingAction: null // 待执行的操作
        }
    },
    mounted() {

    },
    methods: {
        // 处理取消选择课程
        handleUnselectCourse() {
            // 检查是否有选中的知识点
            if (this.selectedKnowledge.length > 0) {
                // 显示确认对话框
                this.confirmActionType = 'close';
                this.pendingAction = () => {
                    this.clearSelectedKnowledge();
                    this.$emit('unselect-course');
                };
                this.showSwitchConfirm = true;
            } else {
                // 直接执行取消选择
                this.$emit('unselect-course');
            }
        },
        async fetchKnow() {
            try {
                let res = await fetchKnowledge(this.selectCourse.id);
                if (res && res.data) {
                    // 处理知识点数据，转换为树形结构
                    this.knowledgeData = this.processKnowledgeData(res.data);
                    this.expandedKeys = this.getDefaultExpandedKeys(this.knowledgeData);
                    console.log("获取知识点", this.knowledgeData);
                } else {
                    this.knowledgeData = [];
                }
            } catch (err) {
                console.error("获取知识点错误", err);
                this.$message.error('获取知识点失败，请重试');
                this.knowledgeData = [];
            }
        },

        // 处理知识点数据，确保正确的树形结构
        processKnowledgeData(data) {
            const processNode = (node) => {
                const processed = {
                    id: node.id,
                    label: node.title || node.name || node.label || '未命名',
                    type: node.type || 'point',
                    content: node.content || node.description || '',
                    prerequisites: node.prerequisites || [],
                    children: []
                };

                // 如果有子节点，递归处理
                if (node.children && Array.isArray(node.children) && node.children.length > 0) {
                    processed.children = node.children.map(child => processNode(child));
                } else {
                    // 如果没有子节点，移除 children 属性以避免树形控件显示展开图标
                    delete processed.children;
                }

                return processed;
            };

            if (Array.isArray(data)) {
                return data.map(item => processNode(item));
            } else if (data && typeof data === 'object') {
                return [processNode(data)];
            } else {
                return [];
            }
        },

        // 获取默认展开的节点key
        getDefaultExpandedKeys(data) {
            const keys = [];
            const traverse = (nodes) => {
                nodes.forEach(node => {
                    if (node.type === 'chapter' || node.type === 'sub_chapter') {
                        keys.push(node.id);
                    }
                    if (node.children) {
                        traverse(node.children);
                    }
                });
            };
            traverse(data);
            return keys;
        },

        // 获取节点类型标签类型
        getNodeTagType(type) {
            const typeMap = {
                'chapter': 'danger',
                'sub_chapter': 'warning',
                'point': 'success'
            };
            return typeMap[type] || 'info';
        },

        // 获取节点类型标签文本
        getNodeTypeLabel(type) {
            const labelMap = {
                'chapter': '章节',
                'sub_chapter': '小节',
                'point': '知识点'
            };
            return labelMap[type] || '未知';
        },

        // 处理节点选中事件
        handleNodeCheck(data, checkedInfo) {
            // 使用 $nextTick 确保 DOM 更新完成后再获取选中节点
            this.$nextTick(() => {
                try {
                    // 获取所有选中的节点
                    const checkedNodes = this.$refs.knowledgeTree.getCheckedNodes();

                    // 只保存类型为 'point' 的知识点
                    this.selectedKnowledge = checkedNodes.filter(node => node.type === 'point');

                    console.log('已选择的知识点:', this.selectedKnowledge);

                    // 触发选择变化事件，向父组件传递选中的知识点
                    this.$emit('knowledge-change', this.selectedKnowledge);
                } catch (error) {
                    console.error('处理节点选中事件出错:', error);
                }
            });
        },

        // 全选功能
        selectAll() {
            try {
                const allPointIds = [];
                const traverse = (nodes) => {
                    nodes.forEach(node => {
                        if (node.type === 'point') {
                            allPointIds.push(node.id);
                        }
                        if (node.children && Array.isArray(node.children)) {
                            traverse(node.children);
                        }
                    });
                };
                traverse(this.knowledgeData);

                this.$refs.knowledgeTree.setCheckedKeys(allPointIds);
                this.handleNodeCheck(); // 手动触发更新
            } catch (error) {
                console.error('全选操作出错:', error);
                this.$message.error('全选操作失败');
            }
        },

        // 清空选择
        clearAll() {
            try {
                this.$refs.knowledgeTree.setCheckedKeys([]);
                this.selectedKnowledge = [];
                this.$emit('knowledge-change', this.selectedKnowledge);
            } catch (error) {
                console.error('清空选择出错:', error);
                this.$message.error('清空选择失败');
            }
        },

        // 移除单个选中项
        removeSelectedItem(itemId) {
            try {
                const checkedKeys = this.$refs.knowledgeTree.getCheckedKeys();
                const newCheckedKeys = checkedKeys.filter(key => key !== itemId);
                this.$refs.knowledgeTree.setCheckedKeys(newCheckedKeys);
                this.handleNodeCheck(); // 手动触发更新
            } catch (error) {
                console.error('移除选中项出错:', error);
                this.$message.error('移除选中项失败');
            }
        },

        // 处理子组件的题目生成事件
        handleQuestionGenerated(data) {
            // 转发给父组件
            this.$emit('question-generated', data);
        },

        // 处理子组件的题目保存事件
        handleQuestionSaved(data) {
            // 转发给父组件
            this.$emit('question-saved', data);
        },

        // 处理子组件的题目更新事件
        handleQuestionsUpdated(data) {
            // 转发给父组件
            this.$emit('questions-updated', data);
            console.log('题目已更新，数据:', data);
        },

        // 处理课程切换确认
        handleSwitchConfirm() {
            // 执行待处理的操作
            if (this.pendingAction) {
                this.pendingAction();
                this.pendingAction = null;
            }
            this.showSwitchConfirm = false;
        },

        // 处理课程切换取消
        handleSwitchCancel() {
            // 取消操作，清除待执行的动作
            this.pendingAction = null;
            this.showSwitchConfirm = false;
        },

        // 清空选中的知识点
        clearSelectedKnowledge() {
            try {
                // 清空树形控件的选中状态
                if (this.$refs.knowledgeTree) {
                    this.$refs.knowledgeTree.setCheckedKeys([]);
                }
                // 清空选中的知识点数组
                this.selectedKnowledge = [];
                this.$emit('knowledge-change', this.selectedKnowledge);
                console.log('已清空选中的知识点');
            } catch (error) {
                console.error('清空知识点选择出错:', error);
                this.$message.error('清空知识点选择失败');
            }
        },

        // 检查是否需要确认切换课程
        checkCourseSwitch() {
            if (this.selectedKnowledge.length > 0) {
                this.confirmActionType = 'switch';
                this.pendingAction = () => {
                    this.clearSelectedKnowledge();
                    this.fetchKnow();
                };
                this.showSwitchConfirm = true;
                return false; // 阻止立即切换
            }
            return true; // 允许立即切换
        }
    },
    watch: {
        // 监听 selectCourse 的变化
        selectCourse(newVal, oldVal) {
            // 如果是从有课程切换到另一个课程，且有选中的知识点，则需要确认
            if (oldVal && newVal && oldVal.id !== newVal.id && this.selectedKnowledge.length > 0) {
                // 使用确认对话框
                if (!this.checkCourseSwitch()) {
                    return; // 阻止立即执行，等待用户确认
                }
            }

            if (newVal) {
                this.fetchKnow();
            } else {
                this.knowledgeData = [];
                this.selectedKnowledge = [];
            }
        }
    }
}

</script>

<style>
/* 主容器样式 */
.topic-creation-container {
    border-left: #dfe6ec 1px solid;
    height: 100%;
    display: flex;
    flex-direction: column;
    background: #fff;
}

/* 头部区域样式 */
.header-section {
    flex-shrink: 0;
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
    z-index: 10;
}

/* 内容区域样式 */
.content-wrapper {
    flex: 1;
    overflow-y: auto;
}

/* 箭头按钮样式 */
:deep(.el-button--text) {
    border-radius: 4px;
    transition: all 0.3s ease;
}

:deep(.el-button--text:hover) {
    background-color: #f5f7fa !important;
    color: #409eff !important;
}

:deep(.el-button--text:disabled) {
    color: #c0c4cc !important;
    cursor: not-allowed;
}

/* 知识点选择区域头部样式 */
.knowledge-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 16px;
    padding: 12px 16px;
    background: #f8f9fa;
    border-radius: 6px;
    border: 1px solid #e9ecef;
    flex-wrap: wrap;
    gap: 8px;
}

.knowledge-header h3 {
    margin: 0;
    color: #333;
    font-size: 16px;
    font-weight: 600;
    flex-shrink: 0;
}

.knowledge-header .el-button {
    margin-left: 8px;
}

.selected-count {
    color: #666;
    font-size: 13px;
    margin-left: 12px;
    white-space: nowrap;
}

/* 加载状态样式 */
.loading-state {
    text-align: center;
    padding: 40px 20px;
    color: #909399;
    background: #fafafa;
    border-radius: 6px;
    border: 1px dashed #dcdfe6;
}

.loading-state .el-icon {
    font-size: 24px;
    margin-bottom: 8px;
    display: block;
}

/* 树形控件样式 */
.knowledge-tree {
    border: 1px solid #e4e7ed;
    border-radius: 6px;
    padding: 12px;
    background: #fff;
    max-height: 500px;
    overflow-y: auto;
}

/* 自定义树节点样式 */
.custom-tree-node {
    flex: 1;
    display: flex;
    flex-direction: column;
    padding: 4px 0;
    /* height: 32px; */
    height: auto !important;
}

.el-tree-node__content {
    display: flex !important;
    align-items: center !important;
    padding: 0 8px;
    height: auto !important;
    line-height: 1.4;
    font-size: 14px;
    color: #606266;
}

.node-label {
    display: flex;
    align-items: center;
    margin-bottom: 4px;
    /* height: 300px !important; */
}

.node-type-tag {
    margin-right: 8px;
    flex-shrink: 0;
}

.node-title {
    font-weight: 500;
    color: #303133;
    line-height: 1.4;
}

.node-content {
    font-size: 12px;
    color: #606266;
    margin-left: 56px;
    margin-bottom: 2px;
    line-height: 1.4;
    word-break: break-word;
}

.node-prerequisites {
    margin-left: 56px;
    margin-top: 2px;
}

.node-prerequisites .el-tag {
    margin-right: 4px;
}

/* 已选择知识点区域样式 */
.selected-knowledge {
    margin-top: 20px;
}

.selected-items {
    max-height: 120px;
    overflow-y: auto;
    padding: 8px;
    background: #fafbfc;
    border: 1px solid #e1e4e8;
    border-radius: 6px;
}

.selected-tag {
    margin: 3px 6px 3px 0;
    max-width: 200px;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    display: inline-block;
}

/* 空状态样式 */
.no-course-selected {
    text-align: center;
    padding: 60px 20px;
}

.no-course-selected .el-empty {
    padding: 0;
}

/* 树形控件节点悬停效果 */
:deep(.el-tree-node__content) {
    height: auto !important;
    min-height: 32px;
    padding: 4px 0;
}

:deep(.el-tree-node__content:hover) {
    background-color: #f5f7fa;
}

/* 树形控件节点选中效果 */
:deep(.el-tree-node.is-checked > .el-tree-node__content) {
    background-color: #ecf5ff;
}

/* 树形控件复选框样式 */
:deep(.el-checkbox__input.is-checked .el-checkbox__inner) {
    background-color: #409eff;
    border-color: #409eff;
}

/* 滚动条样式 */
.knowledge-tree::-webkit-scrollbar,
.selected-items::-webkit-scrollbar,
.content-wrapper::-webkit-scrollbar {
    width: 6px;
    height: 6px;
}

.knowledge-tree::-webkit-scrollbar-track,
.selected-items::-webkit-scrollbar-track,
.content-wrapper::-webkit-scrollbar-track {
    background: #f1f1f1;
    border-radius: 3px;
}

.knowledge-tree::-webkit-scrollbar-thumb,
.selected-items::-webkit-scrollbar-thumb,
.content-wrapper::-webkit-scrollbar-thumb {
    background: #c1c1c1;
    border-radius: 3px;
}

.knowledge-tree::-webkit-scrollbar-thumb:hover,
.selected-items::-webkit-scrollbar-thumb:hover,
.content-wrapper::-webkit-scrollbar-thumb:hover {
    background: #a8a8a8;
}

/* 响应式设计 */
@media (max-width: 768px) {
    .knowledge-header {
        flex-direction: column;
        align-items: flex-start;
    }

    .knowledge-header h3 {
        margin-bottom: 8px;
    }

    .selected-count {
        margin-left: 0;
    }
}
</style>